package com.jtask.mvp.view;

import static com.utils.Strings.concats;
import roboguice.activity.RoboActivity;
import roboguice.inject.ContentView;
import roboguice.inject.InjectView;
import roboguice.util.Ln;
import android.content.Intent;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeRequestUrl;
import com.jtask.AppConstants;
import com.jtask.R;

@ContentView(R.layout.activity_add_account)
public class AddAccount extends RoboActivity implements AppConstants {
	private final String authorizationUrl = new GoogleAuthorizationCodeRequestUrl(
			CLIENT_ID, REDIRECT_URL, SCOPES).build();
	@InjectView(R.id.wvGmailAccount)
	private WebView wvGmailAccount;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		wvGmailAccount.setWebViewClient(new AddAccountWebViewClient());

		wvGmailAccount.loadUrl(authorizationUrl);
	}

	protected void processResultOk(String tokenResult) {
		Intent response = new Intent();
		response.putExtra(K_TOKEN_RESULT, tokenResult);
		setResult(RESULT_OK, response);
		finish();
	}

	protected void processResultError() {
		setResult(RESULT_CANCELED);
		finish();
	}

	private class AddAccountWebViewClient extends WebViewClient {

		@Override
		public void onPageFinished(WebView view, String url) {
			String title = view.getTitle();
			if (title != null && title.toLowerCase().startsWith(SUCCESS_CODE)) {
				Ln.i(title);
				processResultOk(title.substring(title.indexOf("=") + 1));
			}

		}

		@Override
		public void onReceivedError(WebView view, int errorCode,
				String description, String failingUrl) {
			Ln.i(concats(" ", "ERROR", errorCode, "DESC", description,
					"FAILING_URL", failingUrl));
			processResultError();
		}

	}

}
